﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace _4_09_序列化集合
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        List<Student> stuList = new List<Student>();

        private void Form1_Load(object sender, EventArgs e)
        {
            this.BindData();
        }

        private void BindData() {
            if (!File.Exists("list.ini"))
            {
                return;
            }
            else
            {
                FileStream fs = new FileStream("list.ini", FileMode.Open, FileAccess.ReadWrite);
                BinaryFormatter bf = new BinaryFormatter();
                stuList = (List<Student>)bf.Deserialize(fs);
                this.listView1.Items.Clear();
                foreach (Student item in stuList)
                {
                    ListViewItem listViewItem = new ListViewItem(item.StuId.ToString());
                    listViewItem.SubItems.Add(item.StuName);
                    listViewItem.SubItems.Add(item.StuAge.ToString());
                    this.listView1.Items.Add(listViewItem);
                }
                fs.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Student student = new Student();
            student.StuId = Convert.ToInt32(this.idText.Text);
            student.StuName = this.nameText.Text;
            student.StuAge = Convert.ToInt32(this.agetext.Text);
            stuList.Add(student);
            FileStream fs = new FileStream("list.ini", FileMode.Create, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, stuList);
            fs.Close();
            MessageBox.Show("添加成功");
            this.BindData();
        }
    }
}
